import Vue from 'vue'
import Router from 'vue-router'
import layout from '@/layout/index'
import store from '@/store'
import {getAuthorities} from '@/api/system/system.js'

Vue.use(Router)

const originalPush = Router.prototype.push
const originalReplace = Router.prototype.replace
//push
Router.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => console.log(err))
}
//replace
Router.prototype.replace = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
    return originalReplace.call(this, location).catch(err => err)
}


const router = new Router({
    routes: [
        {
            path: '/login',
            name: 'login',
            component: () => import('@/views/login')
        },
        {
            path: '/',
            redirect: '/login',
            component: () => import('@/views/login')
        },
        {
            path: '/home',
            component: layout
        },
        
    ]
})
// to：来源地址，from：跳转地址，next：放行函数next()-直接放行，next('/path')放行并跳转到指定路径
// 路由导航守卫
// 动态路由
let ignorePath = [
    '/login'
]
let refreshOnece = true
router.beforeEach((to, from, next) => {
    if (!ignorePath.includes(to.path) && store.state.isRefresh) {
        getAuthorities().then(res => {
            store.dispatch('set_router', JSON.stringify(res.data.data.authorities))
            store.dispatch('set_refresh', false)
            var data = dynamicRouter(res.data.data.authorities)
            router.addRoute(data)
            next({
                ...to,
                replace: true
            })
        })
    }else if (refreshOnece && store.state.routerData && store.state.routerData.length > 0) {
        let authorities = []
        refreshOnece = false
        store.dispatch('set_refresh', false)
        authorities = JSON.parse(store.state.routerData)
        var data = dynamicRouter(authorities)
        router.addRoute(data)
        next({
            ...to,
            replace: true
        })
    } else {
        next()
    }
    
})
function dynamicRouter(routerData) {
    let mainRouter = {
        path: '/main',
        component: layout,
        children: []
    }
    routerData.forEach(item => {
        if (item.authorityType != 0) {
            mainRouter.children.push({
                 path: item.authorityPath,
                 component: () => import(`@/views/${item.authorityComponent}`)
            })
        }
                        
    })
    return mainRouter
}

export default router